package com.example.token.controller;

import com.example.token.entity.User;
import com.example.token.utils.JwtUtil;
import com.example.token.utils.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@Slf4j
public class UserController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;

    private final String USERNAME = "zhang";
    private final String PASSWORD = "123456";

    private final Long TIMEOUT = 60L; // 有效期半小时

    @PostMapping("/login")
    public Result login(@RequestBody User user) throws JsonProcessingException {
        if (USERNAME.equals(user.getUsername()) && PASSWORD.equals(user.getPassword())) {
            String token = jwtUtil.createToken();
            redisTemplate.opsForValue().set(token, user.getUsername(), TIMEOUT, TimeUnit.SECONDS);
            user.setToken(token);
            log.info("登录成功");
            return Result.success(user);
        }
        log.info("登录失败");
        return Result.fail("账号或密码错误");
    }

    @GetMapping("test")
    public Result test() {
        return Result.success("token213");
    }
}
